package uc108.com.jetpackdemo.activity;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import uc108.com.jetpackdemo.R;
import uc108.com.jetpackdemo.adapter.GameListAdapter;
import uc108.com.jetpackdemo.databinding.ActivityGamelistBinding;
import uc108.com.jetpackdemo.room.DatabaseManager;
import uc108.com.jetpackdemo.room.Game;
import uc108.com.jetpackdemo.room.GameDao;
import uc108.com.jetpackdemo.viewmodel.GameViewModel;

public class GameListActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gamelist);
        ActivityGamelistBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_gamelist);

        GameDao gameDao = DatabaseManager.getAppdatabase(getApplication()).gameDao();
        final Game game = gameDao.getAll().get(0);
        binding.setGame(game);

        RecyclerView recyclerView = findViewById(R.id.recycler);
        final GameListAdapter adapter = new GameListAdapter(gameDao.getAll());

        ViewModelProviders.of(this)
                .get(GameViewModel.class)
                .getDatas().observe(this,
                new Observer<List<Game>>() {
                    @Override
                    public void onChanged(List<Game> games) {
                        adapter.setDatas(games);
                        adapter.notifyDataSetChanged();
                    }
                });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(adapter);
    }

    public void delete(View view) {
        GameDao gameDao = DatabaseManager.getAppdatabase(getApplication()).gameDao();
        gameDao.deleteAll();

        List<Game> all = gameDao.getAll();

        ViewModelProviders.of(this)
                .get(GameViewModel.class).setData(all);

    }
}
